package com.chentianyu.learn.javalinkmysql;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "login",value = "/login")
public class LoginServlet extends HttpServlet {
    String url = "jdbc:mysql://localhost:3306/java_accout";
    String username = "root";
    String password = "1234567890";
    public void init(){}

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        String name = request.getParameter("username");
        String userPassword = request.getParameter("userPassword");

        try {
            Connection connection = DriverManager.getConnection(url, username, password);
            // 在此处执行 SQL 查询
            String sql = "select * from users where username=? and password=?";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1,name);
            stmt.setString(2,userPassword);
//            ResultSet rs = stmt.executeQuery();
            PrintWriter out = response.getWriter();
            try(ResultSet rs = stmt.executeQuery()){
                if (rs.next()) {
                    String uid = rs.getString("uid");
                    String username = rs.getString("username");
                    out.println("用户名:"+username+"  "+"用户uid:"+uid);

                    rs.close();
                    stmt.close();
                    connection.close();
                } else {
                    out.println("error:"+"用户不存在(请先"+"<a href='welcome.jsp'>注册</a>"+")或者用户名密码错误,<a href='updateUser.jsp'>找回密码</a>");
                }
            }


            // 处理结果集
//            while (rs.next()) {
//                // 从结果集中获取数据
//
//            }
            // 关闭连接

        } catch (SQLException e) {
            // 处理连接错误
            e.printStackTrace();

        }

    }
}
